<template>
  <div class="app-container p-6">
    <div class="card" style="max-width:680px;margin:0 auto;">
      <div class="d-flex items-center mb-4" style="gap:8px;">
        <div class="text-primary" style="font-weight:600;">文件分享</div>
        <el-tag v-if="info?.shareType === 1" type="success" size="small">公开</el-tag>
        <el-tag v-else type="warning" size="small">私密</el-tag>
      </div>

      <el-skeleton v-if="loading" :rows="4" animated />

      <template v-else>
        <el-result v-if="error" icon="error" title="分享不可用" :sub-title="error">
          <template #extra>
            <el-button type="primary" @click="reload">重试</el-button>
          </template>
        </el-result>

        <div v-else class="bg-panel radius-lg p-4">
          <div class="mb-3">
            <div>分享码：{{ code }}</div>
            <div v-if="info?.validUntil">有效期：{{ info?.validUntil }}</div>
            <div>访问：{{ info?.accessCount }}，下载：{{ info?.downloadCount }}</div>
          </div>

          <el-form v-if="info?.shareType === 0 && !validated" label-width="80px" @submit.prevent>
            <el-form-item label="访问密码">
              <el-input v-model="password" type="password" show-password placeholder="请输入密码" style="max-width:320px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="doValidate" :loading="validating">验证</el-button>
            </el-form-item>
          </el-form>

          <div v-else class="d-flex" style="gap:12px;">
            <el-button type="primary" @click="download" :loading="downloading">
              <el-icon><download /></el-icon>
              下载文件
            </el-button>
          </div>
        </div>
      </template>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { shareApi, type ShareLinkVO } from '@/api/share'
import { Download } from '@element-plus/icons-vue'

const route = useRoute()
const code = route.params.code as string
const base = import.meta.env.VITE_API_BASE_URL || '/api'

const loading = ref(false)
const error = ref('')
const info = ref<ShareLinkVO | null>(null)
const password = ref('')
const validated = ref(false)
const validating = ref(false)
const downloading = ref(false)

const load = async () => {
  loading.value = true
  error.value = ''
  try {
    const { data } = await shareApi.infoByCode(code)
    if (!data) {
      error.value = '分享不存在或已失效'
      return
    }
    info.value = data
  } catch (e: any) {
    error.value = e?.message || '加载失败'
  } finally {
    loading.value = false
  }
}

const doValidate = async () => {
  if (!password.value) return ElMessage.warning('请输入访问密码')
  validating.value = true
  try {
    await shareApi.validate(code, password.value)
    validated.value = true
    ElMessage.success('验证通过')
  } catch (e: any) {
    ElMessage.error(e?.message || '验证失败')
  } finally {
    validating.value = false
  }
}

const download = async () => {
  try {
    downloading.value = true
    const url = `${base}/file/share/download/${code}`
    const response = await axios.post(url, { password: password.value || undefined }, { responseType: 'blob' })
    const blob = new Blob([response.data])
    const objectUrl = window.URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = objectUrl
    a.download = info.value?.description || 'download'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    window.URL.revokeObjectURL(objectUrl)
    ElMessage.success('开始下载')
  } catch (e: any) {
    ElMessage.error(e?.response?.data?.message || e?.message || '下载失败')
  } finally {
    downloading.value = false
  }
}

const reload = () => load()

onMounted(load)
</script>

<style scoped>
</style>


